import 'package:app_tracking_transparency/app_tracking_transparency.dart';
import 'package:bigegg/common/sp/xmm_shared_preferences_util.dart';
import 'package:bigegg/global/routes/xmm_routes.dart';
import 'package:bigegg/global/xmm_h5_url.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';

import '../../global/user/xmm_account_manager.dart';
import '../../global/xmm_app_const.dart';
import '../../res/xmm_img.dart';
import 'xmm_login_controller.dart';

class XmmLoginPage extends StatefulWidget {
  const XmmLoginPage({super.key});

  @override
  State<StatefulWidget> createState() {
    return XmmLoginPageState();
  }
}

class XmmLoginPageState extends State<XmmLoginPage> {
  XmmLoginController controller = Get.find<XmmLoginController>();

  final TapGestureRecognizer _userAgreementTapGesture = TapGestureRecognizer();
  final TapGestureRecognizer _privacyPolicyTapGesture = TapGestureRecognizer();

  final _isCheckAgreement = false.obs;

  bool _isAppleLogin = false;

  @override
  void initState() {
    super.initState();

    WidgetsFlutterBinding.ensureInitialized()
        .addPostFrameCallback((_) => initPlugin());

    _userAgreementTapGesture.onTap =
        () => XmmRoutes.routeWebPage(XmmH5Url.userAgreement);
    _privacyPolicyTapGesture.onTap =
        () => XmmRoutes.routeWebPage(XmmH5Url.privacyPolicy);

    ///自动登录
    if (XmmAccountManager.instance.isSupportAutoLogin) {
      controller.autoLogin();
    }
  }

  Future<void> initPlugin() async {
    if (XmmSPUtil.get(XmmAppConst.spLoginInfoKey) != null) {
      return;
    }
    final TrackingStatus status =
        await AppTrackingTransparency.trackingAuthorizationStatus;
    if (status == TrackingStatus.notDetermined) {
      await AppTrackingTransparency.requestTrackingAuthorization();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage(XmmImg.loginBg),
            fit: BoxFit.cover,
          ),
        ),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            getAppleLoginWidget(),
            const SizedBox(height: 32),
            getFastLoginWidget(),
            const SizedBox(height: 46),
            getButtonPrivacyWidget(),
            const SizedBox(height: 46),
          ],
        ),
      ),
    );
  }

  Widget getAppleLoginWidget() {
    return GestureDetector(
      child: Container(
        width: 311,
        height: 54,
        decoration: BoxDecoration(
            color: const Color(0xff202020),
            borderRadius: BorderRadius.circular(8)),
        child: Row(mainAxisAlignment: MainAxisAlignment.center, children: [
          Image.asset(XmmImg.appleLogo, width: 24, height: 24),
          const SizedBox(width: 16),
          const Text(
            "Sign in with Apple",
            style: TextStyle(fontSize: 16, color: Colors.white),
          )
        ]),
      ),
      onTap: () => appleLogin(),
    );
  }

  Widget getButtonPrivacyWidget() {
    return Row(mainAxisAlignment: MainAxisAlignment.center, children: [
      Transform.scale(
        scale: 0.8,
        child: Obx(() => Checkbox(
            shape: const CircleBorder(),
            checkColor: Colors.white,
            activeColor: const Color(0xff3CA0D9),
            value: _isCheckAgreement.value,
            side: MaterialStateBorderSide.resolveWith(
              (Set<MaterialState> states) {
                if (states.contains(MaterialState.selected)) {
                  //修改勾选时边框颜色
                  return const BorderSide(width: 2, color: Color(0xff3CA0D9));
                }
                //修改默认时边框颜色
                return const BorderSide(width: 2, color: Colors.white);
              },
            ),
            onChanged: (it) => _isCheckAgreement.value = it ?? false)),
      ),
      Text.rich(
        style: const TextStyle(height: 1.5),
        TextSpan(children: [
          const TextSpan(
              text: "By using our App you agree with our\n",
              style: TextStyle(color: Colors.white, fontSize: 14)),
          TextSpan(
              text: "Term of Use ",
              style: const TextStyle(
                color: Color(0xff3CA0D9),
                fontSize: 14,
                decoration: TextDecoration.underline,
              ),
              recognizer: _userAgreementTapGesture),
          const TextSpan(
              text: "and", style: TextStyle(color: Colors.white, fontSize: 14)),
          TextSpan(
              text: " Privacy Policy.",
              style: const TextStyle(
                color: Color(0xff3CA0D9),
                fontSize: 14,
                decoration: TextDecoration.underline,
              ),
              recognizer: _privacyPolicyTapGesture),
        ]),
      )
    ]);
  }

  Widget getFastLoginWidget() {
    return GestureDetector(
      child: Container(
        width: 311,
        height: 54,
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(8),
        ),
        child: Row(mainAxisAlignment: MainAxisAlignment.center, children: [
          Image.asset(XmmImg.fastLoginLogo, width: 24, height: 24),
          const SizedBox(width: 16),
          const Text(
            "Fast Login",
            style: TextStyle(fontSize: 16, color: Color(0xff1CCDAD)),
          )
        ]),
      ),
      onTap: () => fastLogin(),
    );
  }

  void appleLogin() {
    _isAppleLogin = true;
    if (_isCheckAgreement.isFalse) {
      showPrivacyDialog();
    } else {
      controller.appleLogin();
    }
  }

  void fastLogin() {
    _isAppleLogin = false;
    if (_isCheckAgreement.isFalse) {
      showPrivacyDialog();
    } else {
      controller.fastLogin();
    }
  }

  void showPrivacyDialog() {
    showDialog(
      context: context,
      builder: (context) {
        return SimpleDialog(
          backgroundColor: Colors.transparent,
          children: [
            Container(
              width: 315,
              height: 278,
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(12),
              ),
              alignment: Alignment.center,
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  ClipRRect(
                    borderRadius: BorderRadius.circular(12),
                    child: Image.asset(XmmImg.appLogo, width: 52, height: 52),
                  ),
                  const SizedBox(height: 14),
                  const Text("RallyRound",
                      style: TextStyle(
                          color: Color(0xff404040),
                          fontSize: 16,
                          fontStyle: FontStyle.italic,
                          fontWeight: FontWeight.bold)),
                  const SizedBox(height: 16),
                  Text.rich(
                    TextSpan(children: [
                      const TextSpan(
                          text: "By using our App you agree with our\n",
                          style: TextStyle(
                              color: Color(0xff404040), fontSize: 14)),
                      TextSpan(
                          text: "Term of Use",
                          style: const TextStyle(
                              color: Color(0xff15E8C2), fontSize: 14),
                          recognizer: _userAgreementTapGesture),
                      const TextSpan(
                          text: " and ",
                          style: TextStyle(
                              color: Color(0xff404040), fontSize: 14)),
                      TextSpan(
                          text: "Privacy Policy.",
                          style: const TextStyle(
                              color: Color(0xff15E8C2), fontSize: 14),
                          recognizer: _privacyPolicyTapGesture),
                    ]),
                    textAlign: TextAlign.center,
                    style: const TextStyle(height: 1.5),
                  ),
                  const SizedBox(height: 24),
                  GestureDetector(
                    child: Container(
                      width: 198,
                      height: 40,
                      decoration: BoxDecoration(
                          color: const Color(0xff15E8C2),
                          borderRadius: BorderRadius.circular(8)),
                      alignment: Alignment.center,
                      child: const Text(
                        "Agree and Continue",
                        style: TextStyle(fontSize: 14, color: Colors.white),
                      ),
                    ),
                    onTap: () {
                      Navigator.pop(context);
                      _isCheckAgreement.value = true;
                      if (_isAppleLogin) {
                        appleLogin();
                      } else {
                        fastLogin();
                      }
                    },
                  ),
                  const SizedBox(height: 16),
                  GestureDetector(
                    child: const Text(
                      "Cancel",
                      style: TextStyle(fontSize: 14, color: Color(0x4D000000)),
                    ),
                    onTap: () {
                      Navigator.pop(context);
                    },
                  ),
                ],
              ),
            )
          ],
        );
      },
    );
  }

  @override
  void dispose() {
    super.dispose();
    _userAgreementTapGesture.dispose();
    _privacyPolicyTapGesture.dispose();
  }
}
